package lt.f2g.services.security;

import java.util.Collections;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import lt.f2g.domain.security.UserProfile;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * @author Linas Jakaitis
 */
@Service(value="f2gUserDetails")
public class F2GUserDetailsImpl implements UserDetailsService {

    @PersistenceContext
    private EntityManager em;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	Query query = em.createQuery("from UserProfile p where p.username=:username");
	query.setParameter("username", username);
	try {
	    UserProfile user = (UserProfile) query.getSingleResult();
	    return new User(user.getUsername(), user.getPassword(), true, true, true, true, Collections.<GrantedAuthority>emptyList());
	} catch (Exception e) {
	   throw new UsernameNotFoundException(e.getMessage());
	}
    }

}